<template>
  <header class="main-header">
    <div style="margin:0 15px;position:relative">
      <div class="top-logo">
        <router-link to='/' class="a-link">
          <span class="logo-span">Tiny Chart</span>
        </router-link>
      </div>
      <nav class="top-menu">
        <ul>
          <li v-for="item in menu" :class="{'active':activeId==item.name}">
            <a href="#" @click.stop.prevent="goTo(item)">
              <f-a :name="item.meta.icon"></f-a>
              {{item.meta.title}}</a>
          </li>
        </ul>
      </nav>
      <div class="top-right">
        <el-button round>退出</el-button>
      </div>
    </div>
  </header>
</template>

<script>
  import {Auth} from '../resources';
  import route from '../route';

  export default {
    props: ['toRoute'],
    data() {
      return {
        activeId: '',
        menus: []
      };
    },
    computed: {
      user: function () {
        return Object.assign({}, {userName: '', userAccount: '', userLastLoginTime: 0}, this.$store.state.user);
      },
      menu: function () {
        let menuShow = [];
        this.menus.forEach(item => {
          menuShow.push(item);
        });
        return menuShow;
      }
    },
    watch: {
      toRoute: function () {
        this.getGroupId();
      }
    },
    methods: {
      goTo: function (item) {
        let path = item.path;
        for (let key in this.$route.params) {
          path = path.replace(':' + key, this.$route.params[key]);
        }
        this.$router.push({path: path});
      },
      getGroupId: function () {
        if (this.toRoute && this.toRoute.path !== undefined && this.toRoute.meta && this.toRoute.meta.moduleId) {
          this.activeId = this.toRoute.meta.moduleId;
        }
      },
      logout: function () {
        window.localStorage.setItem('lastUrl', window.location.href);
        Auth.logout().then(() => {
          window.localStorage.setItem('userId', this.$store.state.user.userId);
          //          window.localStorage.removeItem('user');
          return this.$router.replace('/login');
        });
      }
    },
    mounted: function () {
      let nodes = route.filter(item => {
        return item.name === 'project';
      });
      if (nodes.length > 0) {
        this.menus = nodes[0].children;
      }
      this.getGroupId();
    }
  };
</script>
